﻿<!DOCTYPE html>
<html lang="utf-8">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0,minimum-scale=1.0, user-scalable=no" />
<link rel="shortcut icon" href="/Images/ico/favicon.ico" type="image/x-icon">
<link rel="stylesheet" type="text/css" href="/css/swiper.min.css" />
<link rel="stylesheet" type="text/css" href="/css/style.css" />
<link rel="stylesheet" type="text/css" href="/css/isCategory.css">
<link type="text/css" rel="stylesheet" href="/layui/css/layui.css"  media="all">
<script type="text/javascript" src="/layui/layui.js" charset="utf-8"></script>
<script src="/js/jquery.min.js" type="text/javascript"></script>
<script src="/js/swiper.min.js" type="text/javascript"></script>
<script type="text/javascript" src="/js/custom.js"></script>
<script type="text/javascript" src="/js/layui-post.js"></script>
<style type="text/css">
.layui-layer-nobg{border-radius: 15px!important;background:#FFFFFF!important;}
.layui-layer-title{border-radius: 15px 15px 0 0!important;}
.layui-layer-content{border-radius: 0 0 15px 15px;}
.choosespace{position: absolute;margin-left: 50px; border: 1px solid red;border-radius: 50%; background: red;color: white;padding: 1px;font-size: 10px;width: 11px;height: 11px;text-align: center; line-height: 11px;}
.lists div.l {width: 26%}
.lists div.r {width: 74%}
.his-search {max-width: 30vw;color: #000;border-radius: 5px;background: #f3f2f2;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;}
.discount{color:#595858;font-size: 10px;}
</style>
</head>
<body>
<div class="loca ng-scope title-order" style="background: #f9fafd;">
    <a class="title-top" href="javascript:window.location.href='/shop';" onclick="insertBachCart(1)"></a>
    <a class="title-center" style="width: 86%;">
        <div style="height: 10px;"></div>
        <div style="border-radius: 20px;background: #fff;height: 35px;line-height: 30px;text-align: right;font-size: 14px;">
            <i class="layui-icon layui-icon-search" style="vertical-align: sub;"></i>
            <input id="goodsName" type="text" class="layui-input-inline" placeholder="搜索您要的商品" style="border: none;font-size:12px;font-weight:normal;height: 24px;width: 76%;">
            <button style="height: 24px;margin-right: 5px;text-align: center;border-radius: 20px;width: 45px;" class="layui-btn layui-btn-danger layui-btn-xs" onclick="queryGoods()">搜索</button>
        </div>
    </a>
</div>
<div style="height: 50px;"></div>
<div class="sort_container" id="sort_container" style="margin-bottom: 50px;">
    <!--历史搜索-->
    <div id="historySearch" style="padding: 5px; height: 35px; line-height: 35px; border-bottom: 1px solid #efebeb;display: none;">
        <div style="width: 100%;height: 40px;line-height: 35px;"><div style="float: left">历史搜索</div><div style="float: right"><i class="layui-icon layui-icon-delete" id="hisClear"></i></div></div>
        <div style="margin-top:10px;" id="hisBtn"></div>
    </div>
    <!--右边商品-->
    <div class="sort_wrap" style="padding-left: 1vw;">
        <ul id="goodsDetail"></ul>
    </div>
</div>
<!--底部结算导航-->
<div class="cart ng-scope" id="carscount" style="display: none">
    <div class="r"><a onclick="insertBachCart()">去结算</a></div>
    <div class="l ng-binding">
        ￥<label id="totalmoney">0</label>
    </div>
    <i id="totalcartnumber" class="ng-binding cartnum">0</i>
    <a onclick="insertBachCart()"><img src="/img/shop_cart01.png" alt="..."></a>
</div>
<!--/底部结算导航-->
</div>
</body>
<script src="/js/isCategory.js"></script>
<script>
$.ajaxSetup({contentType: "application/json; charset=utf-8"});
var userInfo = $.parseJSON(sessionStorage.getItem("userInfo"));
var goodsIds=[],reqdataList=[],enumsData=[],spacesList=[],spacesNameList=[],totalcartnumber = 0,totalmoney = 0;
var historyContents = JSON.parse(localStorage.getItem("history-contents"));
layui.use(['layer','form'], function(){
    historyContents = isEmpty(historyContents) ? [] : historyContents;
    if(historyContents.length > 0){
        $("#historySearch").show()
        for(var i in historyContents) $("#hisBtn").append('<button class="layui-btn layui-btn-xs his-search" value="'+historyContents[i]+'">'+historyContents[i]+'</button>')
    }else{
        $("#historySearch").hide()
    }
    $.post(geturl()+'/enums/select?token='+sessionStorage.getItem("token"), JSON.stringify({parentEnumCode:"PRODUCT_TYPE<->DELIVERY_TYPE",orderByAscType:"enumCode"}), function (res) {
        $("#productType").html("")
        $("#goodsDetail").html("")
        enumsData = res.data
    })
    $("#hisBtn button").click(function(){
        $("#carscount").show()
        $("#historySearch").hide()
        insertBachCart(1)
        $("#goodsName").val($(this).val())
        showGoods($(this).val())
    })
    $("#hisClear").click(function(){
        $("#hisBtn").empty()
        $("#historySearch").hide()
        historyContents = []
        localStorage.setItem("history-contents",JSON.stringify(historyContents))
    })
})

function showGoods(goodsName){
    $("#productType").html("")
    $("#goodsDetail").html("")
    $.post("/cateringGoods/selectDisc",JSON.stringify({status:0}),function (res){
        for(var i in res.data){
            var tab = (i == 0 ? "on" : '')
            $("#productType").append(
                '<li class="'+tab+'" data-ident="0">'+enums(res.data[i].productType,'PRODUCT_TYPE')+'</li>'
            )
            $("#goodsDetail").append(
                '<ul class="product lists" id="'+res.data[i].productType+'" data-ident="0"></ul></element>'
            )
        }
    })
    $.post("/cateringGoods/select",JSON.stringify({status:0}),function (res){
        for(let i in res.data){
            var displayStatus = res.data[i].goodsName.indexOf(goodsName) > -1 ? 'block' : 'none';
            $("#"+res.data[i].productType).append(
                '<li price="'+(res.data[i].goodsPrice/1*res.data[i].discount/10).toFixed(2)+'" id="'+res.data[i].sysId+'li" goodsId="'+res.data[i].sysId+'" style="width: 100%;display:'+displayStatus+'">' +
                '<div class="l view">' +
                '<a onclick="window.location.href=\'/detail?sysId='+res.data[i].sysId+'\'"><img src="'+res.data[i].goodsImg+'" style="border-radius: 10px;" class="img-responsive" alt="..." /></a>' +
                '</div>' +
                '<div class="r">' +
                '<p class="t">'+getGoodsNameColor(res.data[i].goodsName)+'</p>' +
                '<div class="remark">'+res.data[i].remark+'</div>' +
                '<div class="jifen" style="display: '+(res.data[i].interNum == 0?'none':'block')+'">送积分：'+res.data[i].interNum+'</div>' +
                '<p class="discount" style="display: '+(res.data[i].discount=="10.00"?'none':'block')+'">'+cutZero(res.data[i].discount)+'折</p>' +
                getTooles(res.data[i])+
                '</div>' +
                '</li>'
            )
        }
    }).done(function (){
        //查询购物车的数据
        $.post("/cateringCart/select",JSON.stringify({userId:userInfo.userId}),function(res){
            reqdataList = [];goodsIds = [];totalcartnumber = 0;totalmoney = 0
            for(var i in res.data){
                $("#"+res.data[i].goodsId+"cart").text(res.data[i].goodsPrice)
                //只针对可选择规格的修改price
                $("#"+res.data[i].goodsId+"lic").attr("price",res.data[i].goodsPrice)
                totalcartnumber += res.data[i].goodsNum
                totalmoney += res.data[i].goodsNum*res.data[i].goodsPrice
                $("#"+res.data[i].goodsId).text(res.data[i].goodsNum)
                $("#"+res.data[i].goodsId+"li").addClass("on")
                //将数据放入购物车
                if(goodsIds.indexOf(res.data[i].goodsId) === -1) {
                    $("#"+res.data[i].goodsId+"cnum").show()
                    $("#"+res.data[i].goodsId+"cnum").text(res.data[i].goodsNum)
                    let resdata = {};
                    goodsIds.push(res.data[i].goodsId)
                    resdata.goodsId = res.data[i].goodsId;
                    resdata.goodsNum = res.data[i].goodsNum
                    resdata.goodsPrice = res.data[i].goodsPrice
                    resdata.spacesId = res.data[i].spacesId
                    if(!isEmpty(res.data[i].spacesId)) $("#"+res.data[i].goodsId).parent().parent().parent().find(".price").html("￥"+res.data[i].goodsPrice)
                    resdata.userId = userInfo.userId
                    reqdataList.push(resdata);
                }
            }
            $("#totalcartnumber").text(totalcartnumber);
            $("#totalmoney").text(totalmoney.toFixed(2));
        })
        //shop：加入购物车
        $(".lists li").each(function () {
            var objLi = $(this);
            //点击购物车
            $(objLi).find(".join").click(function () {
                $(objLi).addClass("on");
                $(objLi).find(".number").text(1);
                var goodsId =$(objLi).attr("goodsId");
                var reqdata={};
                var number = parseInt($(objLi).find(".number").text());
                if(goodsIds.indexOf(goodsId) === -1) {
                    goodsIds.push(goodsId)
                    reqdata.goodsId = goodsId;
                    reqdata.goodsNum = number
                    reqdata.goodsPrice = $(objLi).attr("price")
                    reqdata.userId = userInfo.userId
                    reqdataList.push(reqdata);
                }else {
                    for(var i in reqdataList){
                        if(reqdataList[i].goodsId === goodsId) reqdataList[i].goodsNum = number;
                    }
                }
                CountNumPrice();
            });
            //点击减数量
            $(objLi).find(".num_l").click(function () {
                var goodsId =$(objLi).attr("goodsId");
                var number = parseInt($(objLi).find(".number").text()) - 1;
                var cart = $(objLi).attr("cart");
                if (number > 0) {
                    $(objLi).find(".number").text(number);
                    if(goodsIds.indexOf(goodsId) > -1){
                        for(var i in reqdataList){
                            if(reqdataList[i].goodsId === goodsId) reqdataList[i].goodsNum = number;
                        }
                    }
                } else {
                    if(goodsIds.indexOf(goodsId) > -1) {
                        goodsIds.splice($.inArray(goodsId,goodsIds),1)
                        reqdataList.splice($.inArray(goodsId,reqdataList),1)
                    }
                    if (cart == 1) {//说明是购物车中的操作
                        $(objLi).remove();
                    } else if (cart == 2) {//说明是外卖的操作
                        if (number == 0) {
                            $(objLi).find(".number").text(number);
                        }
                    } else {
                        $(objLi).removeClass("on");
                    }
                }
                CountNumPrice();
            });
            //点击加数量
            $(objLi).find(".num_r").click(function () {
                var goodsId =$(objLi).attr("goodsId");
                var reqdata={};
                var number = parseInt($(objLi).find(".number").text()) + 1;
                if(goodsIds.indexOf(goodsId) === -1) {
                    goodsIds.push(goodsId)
                    reqdata.goodsId = goodsId;
                    reqdata.goodsNum = number
                    reqdata.goodsPrice = $(objLi).attr("price")
                    reqdata.userId = userInfo.userId
                    reqdataList.push(reqdata);
                }else {
                    for(var i in reqdataList){
                        if(reqdataList[i].goodsId === goodsId) reqdataList[i].goodsNum = number;
                    }
                }
                $(objLi).find(".number").text(number);
                CountNumPrice();
            });
            //点击查看产品详情
            $(objLi).find(".view").click(function () {
                $(objLi).find(".detail").show(200);
            });
        });
    })
}

function getTooles(data){
    if(data.goodsStock == 0){
        return '<div style="font-size: 12px;margin-top: 5px;">已售罄</div>';
    }else {
        if(data.isSpaces == 0){
            return '<p class="price"><span style="font-size: 10px;color:red;">￥</span>'+(data.goodsPrice/1*data.discount/10).toFixed(2)+'<span style="font-size: 10px;color:#c0bebe;padding-left: 5px;display: '+(data.discount=="10.00"?'none':'inline')+';text-decoration: line-through;">￥'+data.goodsPrice+'</span></p>' +
                '<div class="showaddcart">' +
                '<img src="img/cart_01.png" class="img-responsive join" id="'+data.sysId+'join" alt="..." />' +
                '<div class="num_con">' +
                '<img src="img/num_l.png" class="img-responsive num_l" alt="..." />' +
                '<span class="number" style="padding: 5px;" id="'+data.sysId+'">0</span>' +
                '<img src="img/num_r.png" class="img-responsive num_r" alt="..." />' +
                '</div>' +
                '</div>'
        }else{
            return '<p class="price"><span style="font-size: 10px;color:red;">￥</span><span class="price-id" id="'+data.sysId+'cart">'+(data.goodsPrice/1*data.discount/10).toFixed(2)+'</span><span style="font-size: 10px;color:#c0bebe;padding-left: 5px;display: '+(data.discount=="10.00"?'none':'inline')+';text-decoration: line-through;">￥'+data.goodsPrice+'</span></p>' +
                '<div class="showaddcart">' +
                '<div class="choosespace" style="display: none;" id="'+data.sysId+'cnum">0</div>'+
                '<img src="img/cart_choose.png" class="img-responsive" onclick="chooseSpaces(\''+data.sysId+'\',\''+data.goodsName+'\')" style="width: 60px;margin-right: 5px;" alt="..." />' +
                '<div class="num_con" style="display:none;">' +
                '<img src="img/num_l.png" class="img-responsive num_l" alt="..." />' +
                '<span class="number" style="padding: 5px;" id="'+data.sysId+'">0</span>' +
                '<img src="img/num_r.png" class="img-responsive num_r" alt="..." />' +
                '</div>' +
                '</div>'
        }
    }
}
function enums(s,enumCode){
    for(var key in enumsData[enumCode]) if(key === s) return enumsData[enumCode][s];
}
function queryGoods(){
    $("#carscount").show()
    $("#historySearch").hide()
    insertBachCart(1)
    showGoods($("#goodsName").val())
    if(!isEmpty($("#goodsName").val()) && historyContents.indexOf($("#goodsName").val()) == -1){
        historyContents.push($("#goodsName").val())
        localStorage.setItem("history-contents",JSON.stringify(historyContents))
    }
}
function insertBachCart(type){
    if(reqdataList.length > 0){
        $.post("/cateringCart/insertBach",JSON.stringify({userId:userInfo.userId,cartslist:reqdataList}),function(res){
            if(type != 1) if(res.success) window.location.href = "/cart"
        })
    }else{
        if(type != 1) layer.msg("购物车空空如也",{icon:0,time:1500})
    }
}
function CountNumPrice() {
    var totalcartnumber = 0;//数量
    var totalmoney = 0;//价格
    $(".lists .on").each(function (i, model) {
        var objLi = $(this);
        var number = parseInt($(objLi).find(".number").text());
        var price = parseFloat($(objLi).attr("price"));
        totalcartnumber = totalcartnumber + number;
        totalmoney = totalmoney + (number * price);
    });
    $(".lists .spaces").each(function (i, model) {
        var objLi = $(this);
        var number = parseInt($(objLi).find(".number").text());
        var price = parseFloat($(objLi).attr("price"));
        totalcartnumber = totalcartnumber + number;
        totalmoney = totalmoney + (number * price);
    });
    $("#totalcartnumber").text(totalcartnumber);
    $("#totalmoney").text(totalmoney.toFixed(2));
}
//弹窗计算价格
function CountNumPriceLayer(id,num,price) {
    $("#"+id).html(num)
    $("#"+id).parent().parent().parent().parent().attr("price",price)
    $("#"+id).parent().parent().parent().find(".price").html("￥"+price)
    if(num/1 > 0) {
        $("#"+id+"cnum").show();
    }else{
        $("#"+id+"cnum").hide();
    }
    $("#"+id+"cnum").text(num);
    CountNumPrice()
}
function getGoodsNameColor(goodsName){
    var goodn = $("#goodsName").val()
    var goodsNewName = '';
    if(goodsName.indexOf(goodn) > -1){
        var names = goodsName.split(goodn)
        for(var i in names) {
            if(names[i] == ''){
                goodsNewName = goodsNewName + '<span style="color:red;">'+goodn+'</span>';
            }else goodsNewName += names[i]
        }
        return goodsNewName;
    }else return goodsName
}
function chooseSpaces(goodsId,goodsName){
    layer.open({
        type:2,
        area: ['90%', '50%'],
        title:[goodsName,'font-size: 16px; font-weight: bold;'],
        closeBtn:1,
        btnAlign: 'c',
        anim: 2,
        skin:'layui-layer-nobg',
        shadeClose:true,
        content:"/choosespaces?goodsId="+goodsId,
        scrollbar:false,
    })
}
</script>
</html>
